package springmvc.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import springmvc.bean.Homework;
import springmvc.dao.StudentHomeworkJdbc;
import springmvc.service.DbService;
import springmvc.service.impl.DbServiceImpl;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
public class StudentController {

    ApplicationContext ac = new ClassPathXmlApplicationContext("springmvc.xml");

    @RequestMapping("/index")
    public String student_index(HttpServletRequest req, HttpServletResponse resp, Model model){
        DbServiceImpl dbService = (DbServiceImpl) ac.getBean("DbServiceImpl");
        String account = null;
        Cookie[] cookies = req.getCookies();
        for(Cookie cookie: cookies){
            if(cookie.getName().equals("account")){
                account = cookie.getValue();
                System.out.println("student-homework-servlet:  "+ account);
            }
        }
        if("get".equalsIgnoreCase(req.getMethod())){
            List<Homework> list = dbService.get_student_homework(account);
            req.setAttribute("list",list);
            return "index";
        }else{
            System.out.println("student——id：" + account);
            String submit_info = req.getParameter("submit");
            System.out.println("student-homework-servlet-homework-submit:  " + submit_info);
            String[] info = submit_info.split(" ");
            String id = info[1];
            String title = req.getParameter("homework_title+"+id);
            String homework_content = req.getParameter("content+"+id);
            System.out.println("student-homework-servlet-homework-content:  " + homework_content);
            System.out.println("student-homework-servlet-homework-id:  "+ id);
            System.out.println("student-homework-servlet-homework-title:  " + title);
            dbService.insert_student_homework(account, id, homework_content,title);
            List<Homework> list = dbService.get_student_homework(account);
            req.setAttribute("list",list);
            return "index";
        }
    }
}
